#! /usr/bin/php
<?php
/*
 * 清理服务器
 * <br />清理 cdr表未归属记录
 * <br />cdr归档
 * <br />cdr truncate
 * <br />tevent_log truncate
 * <br />清理 Runtime目录
 * <br />改造 cdrhistory，可以truncate cdr
 * @since 1.0 2015-11-10 SoChishun <14507247@qq.com>
 * @remark 启动 php -f /var/www/html/xcall_deamon/clear_server.php
 * @remark chkconfig /var/www/html/xcall_deamon/clear_server.php
 */
set_time_limit(0);

$config = include '/var/www/html/xcall/Application/XCall/Conf/config.php';

$link = db_conn();
main();
mysql_close($link);
$redis->close();

function main() {
    // 清理CDR未归属记录
    mysql_query('delete from cdr where siteID is null');
    // CDR归档
}

function db_conn() {
    global $config;
    if (!isset($config) || !$config) {
        echo PHP_EOL . 'Database config is invalid.';
        exit;
    }
    $link = mysql_connect($config['DB_HOST'], $config['DB_USER'], $config['DB_PWD']);
    if (false === $link) {
        echo PHP_EOL . 'Database connect fail:' . mysql_error();
        mysql_close($link);
        exit;
    }
    mysql_query('set names UTF8');
    mysql_select_db($config['DB_NAME']);
    return $link;
}

/**
 * 执行MySQL语句
 * @global array $config
 * @param string $sql
 * @since 1.0 <2015-4-8> SoChishun Added.
 */
function db_execute($sql) {
    $link = db_conn();
    $result = mysql_query($sql, $link);
    if (false === $result) {
        echo PHP_EOL . 'DB execute fail:' . mysql_error();
        mysql_close($link);
        exit;
    }
    mysql_close($link);
}
